package main

import (
	"fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

var DB *sql.DB

func init() {
	database, err := sql.Open("mysql", "admin:admin123@tcp(192.168.3.103:3306)/Golang_week10")
	if err != nil {
		fmt.Println("连接数据库失败:", err)
		return
	}
	DB = database
}

/*
type Person struct {
	ID int `db:"user_id"`
	Username sql.NullString `db:"username"`
	Gender sql.NullString `db:"gender"`
	Email sql.NullString `db:"email"`
}*/

type Person struct {
	ID int
	Username sql.NullString
	Gender sql.NullString
	Email sql.NullString
}

func query() {
	row := DB.QueryRow("select * from person where user_id=?", 5)
	var person = new(Person)
	// row.scan中的字段必须是按照数据库存入字段的顺序，否则报错
	if err := row.Scan(&person.ID, &person.Username, &person.Gender, &person.Email); err != nil {
		fmt.Println("Scan Failed:", err)
		return
	}
	fmt.Println(person)
}

func main() {
	query()
}